import GlobalEvent from "../../cfw/event/GlobalEvent";
import { EventName } from "../Config";
import User from "../../game/db/User";
import ObjectPool from "../../cfw/pool/ObjectPool";
import BagManager from "../../game/bag/BagManager";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MoneyUIView extends cc.Component {

    @property(cc.Label)
    label: cc.Label = null;


    @property(cc.Node)
    coin: cc.Node = null;

    @property(cc.Prefab)
    coinPrefab: cc.Prefab = null;

    private pool: ObjectPool<cc.Node> = new ObjectPool('coin')

    start() {
        GlobalEvent.instance().on(EventName.UPDATE_COIN, this.updateCoin, this)
        GlobalEvent.instance().on(EventName.ADD_COIN, this.addCoin, this)
        this.coin.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this)
        this.updateCoin()
    }

    touchEnd() {
        BagManager.buyCoin()
    }

    onDestroy() {
        GlobalEvent.instance().off(EventName.UPDATE_COIN, this.updateCoin, this)
        GlobalEvent.instance().off(EventName.ADD_COIN, this.addCoin, this)
    }

    addCoin(pos: cc.Vec2, time: number = 0.5) {
        let node = this.pool.get(() => {
            let n = cc.instantiate(this.coinPrefab)
            this.node.addChild(n)
            return n;
        })
        pos = this.node.convertToNodeSpaceAR(pos)
        node.x = pos.x;
        node.y = pos.y;
        node.opacity = 255;
        cc.log(' addCion pos ', pos.x, pos.y)
        cc.tween(node).to(time, { x: this.coin.x, y: this.coin.y }).call(() => {
            node.opacity = 0;
            this.pool.put(node)
        }).start()


    }

    updateCoin() {
        let coin = User.instance().getCoin();
        this.label.string = coin;
    }

    // update (dt) {}
}
